package com.houseman.workFlow.processer.impl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.houseman.workFlow.bean.Line;
import com.houseman.workFlow.bean.TaskArea;
import com.houseman.workFlow.bean.WorkFlowGraph;
import com.houseman.workFlow.processer.Processer;
import com.houseman.workFlow.service.GraphService;
import com.houseman.workFlow.service.impl.GraphServiceImpl;
import com.houseman.workFlow.utils.JsonToGraph;

/**
 * 发布流程
 */
public class PublishProcesser extends Processer{

	@Override
	public void proccess(HttpServletRequest request, HttpServletResponse response) {
		//service
		GraphService service = new GraphServiceImpl();
		
		String gJson = request.getParameter("graph");
		String tJson = request.getParameter("tasks");
		String lJson = request.getParameter("lines");
		
		JsonToGraph util = new JsonToGraph();
		
		WorkFlowGraph graph = util.toGraph(gJson);
		List<TaskArea> tasks = util.toTaskArea(tJson);
		List<Line> lines = util.toLine(lJson);
		
		graph.setTasks(tasks);
		graph.setLines(lines);
		
		outInfo = "发布成功！";
		//保存数据或者更新数据
		try {
			if(graph.getGraphId() != 0) { //更新
				service.updateGraph(graph);
			}else { //保存
				service.savaGraph(graph);
			}
		} catch (Exception e) {
			outInfo = "流程发布失败，请检查数据！";
			e.printStackTrace();
		}
		
		//数据处理后返回处理结果提示
		response.setCharacterEncoding("UTF-8");
		try {
			PrintWriter out = response.getWriter();
			out.print(outInfo);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
